// 常用数据格式校验

/**
 * rule 构造函数
 * @param { 是否必填 } required
 * @param { 校验正则 } regStr
 * @param { 数据中文label } label
 */
const RuleFuc = function (required, regStr, label, msg) {
    this.required = required
    this.validator = (rule, value, callback) => {
        if (required && value === '') {
            callback(new Error(`请输入${label}`))
        } else if (value != '' && !regStr.test(value)) {
            callback(new Error(msg || `请输入正确格式的${label}`))
        } else {
            callback()
        }
    }
    this.trigger = ['blur']
}

export default {
    // 手机号码
    mobile: /^[1]([3-9])[0-9]{9}$/,
    // 固话
    callNum: /^0[1-9][0-9]{1,2}-[2-8][0-9]{6,7}$/,
    // 正整数
    integerPositive: /^\d*\.?\d+$/,
    // email
    email: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
    // 身份证号
    idCard: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
    // URL正则
    urlP: /^((https?|ftp|file):\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/,
    // cn
    cn: /^[\u4e00-\u9fa5]{0,}$/,
    number: /^[0-9]*$/,
    // 金额，精确到两位小数
    $num: /^[0-9]+(.[0-9]{2})?$/,
    // 车牌号正则
    cPattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/,
    // 邮编
    postCode: /^[0-9]{6}$/,
    // 数字和字母
    num_en: /^[0-9a-zA-Z]*$/,
    // 浮点数
    float_num: /[0-9]*\.?[0-9]+/,

    /**
     * 正则表达式 && rules自定义规则统一新增、修改
     * 已在挂载在Vue.prototype.$rules
     * @param { 是否必填，默认是 } required
     */
    callNumRule: function (required = true) {
        return new RuleFuc(required, this.callNum, '传真号码')
    },
    mobileRule: function (required = true) {
        return new RuleFuc(required, this.mobile, '手机号码')
    },
    emailRule: function (required = true) {
        return new RuleFuc(required, this.email, '邮箱')
    },
    postCodeRule: function (required = true) {
        return new RuleFuc(required, this.postCode, '邮政编码')
    },
    floatNumRule: function (required = true) {
        return new RuleFuc(required, this.float_num, '浮点数', '只能输入数字')
    },
    rememberCode: function (required = true) {
        let obj = new RuleFuc(required, this.num_en, '助记码', '助记码只支持数字或字母')
        return obj
    }
}
